package com.cmhi.softmbh.util;

import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.cmhi.softmbh.R;

public class ToastUtils {
    private ToastUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    private static Context context;
    // Toast对象
    private static Toast toast;

    /**
     * 在Application中初始化ToastUtils.init(this)
     *
     * @param context
     */
    public static void init(Context context) {
        ToastUtils.context = context.getApplicationContext();
    }

    /**
     * 发送Toast,默认LENGTH_SHORT
     *
     * @param massage
     */
    public static void show(String massage) {
        showToast(context, massage, Toast.LENGTH_SHORT);
    }


    /**
     * 在UI界面隐藏或者销毁前取消Toast显示
     */
    public static void cancel() {
        if (toast != null) {
            toast.cancel();
            toast = null;
        }
    }

    private static void showToast(Context context, String massage, int duration) {
        //使用布局加载器，将编写的toast_layout布局加载进来
        View view = LayoutInflater.from(context).inflate(R.layout.toast_layout, null);
        if (toast == null) {
            toast = new Toast(context);
        }
        TextView textView = view.findViewById(R.id.textView);
        textView.setText(massage);
        //设置Toast要显示的位置，水平居中并在底部，X轴偏移0个单位，Y轴偏移70个单位，
        toast.setGravity(Gravity.CENTER | Gravity.BOTTOM, 0, dp2px(context, 35));
        //设置显示时间
        toast.setDuration(duration);
        toast.setView(view);
        toast.show();
    }


    /**
     * dp转换为px
     *
     * @param context
     * @param value   单位dp
     * @return
     */
    public static int dp2px(Context context, int value) {
        float v = context.getResources().getDisplayMetrics().density;
        return (int) (v * value + 0.5f);
    }
}
